package com.teacher.service.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.teacher.pojo.entity.AbsentClass;
import com.teacher.pojo.entity.ClassLevel;
import com.teacher.pojo.entity.StuClass;
import com.teacher.pojo.enums.ClassLevelType;
import com.teacher.pojo.excel.AbsentClassExcel;
import com.teacher.pojo.excel.ClassLevelExcel;
import com.teacher.service.IAbsentClassService;
import com.teacher.service.IClassLevelService;
import com.teacher.service.IPerStudentService;
import com.teacher.service.IStuClassService;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: zfm
 * @Date: 2021/7/30 16:17
 */
public class ExcelClassLevelListener extends AnalysisEventListener<ClassLevelExcel> {
    private Long termId;
    private IClassLevelService iClassLevelService;

    private List<ClassLevel> classLevelList = new ArrayList<>();
    private IStuClassService iStuClassService;

    public ExcelClassLevelListener(Long termId, IClassLevelService iClassLevelService, IStuClassService iStuClassService) {
        this.termId = termId;
        this.iClassLevelService = iClassLevelService;
        this.iStuClassService = iStuClassService;
    }

    @Override
    public void invoke(ClassLevelExcel classLevelExcel, AnalysisContext analysisContext) {
        StuClass stuClass = iStuClassService.getOne(new QueryWrapper<StuClass>().lambda()
                .eq(StuClass::getClassName, classLevelExcel.getClassName()).last("limit 1"));
        if (stuClass != null) {
            ClassLevel classLevel = new ClassLevel();
            BeanUtils.copyProperties(classLevelExcel, classLevel);
            classLevel.setClassId(stuClass.getId());
            classLevel.setTermId(termId);
            classLevel.setLevel(classLevelExcel.getLevel().equals(ClassLevelType.A.getType()) ? 10 :
                    classLevelExcel.getLevel().equals(ClassLevelType.B.getType()) ? 20 : 30);
            classLevelList.add(classLevel);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }

    private void saveData() {
        iClassLevelService.saveBatch(classLevelList);
    }
}
